package com.neosavvy.grid.renderer {
    import com.neosavvy.grid.PickFilterGrid;
    import com.neosavvy.grid.PickFilterRow;
    import com.neosavvy.grid.event.PickFilterGridEvent;

    import flash.display.DisplayObject;
    import flash.events.MouseEvent;

    import flash.text.TextField;

    import mx.controls.CheckBox;
    import mx.controls.RadioButton;
    import mx.controls.advancedDataGridClasses.AdvancedDataGridListData;
    import mx.controls.dataGridClasses.DataGridListData;
    import mx.controls.listClasses.BaseListData;

    /***
     * Thanks to this blog location for the code in this file
     * http://www.benclinkinbeard.com/2007/11/efficient-reusable-and-centered-checkbox-renderers-for-datagrids/
     *
     * It was helpful not to have to write these few lines of code.
     */
    public class CenteredRadioButtonItemRenderer extends RadioButton {
        private var _adgListData:AdvancedDataGridListData;
        private var _grid:PickFilterGrid;

        // update data item on click
        override protected function clickHandler(event:MouseEvent):void {
            super.clickHandler(event);
            data[DataGridListData(listData).dataField] = selected;

            dispatchEvent(new PickFilterGridEvent(PickFilterGridEvent.ITEM_SELECTED, data as PickFilterRow));
        }


        override protected function updateDisplayList(w:Number, h:Number):void {
            super.updateDisplayList(w, h);

            var n:int = numChildren;
            for (var i:int = 0; i < n; i++) {
                var c:DisplayObject = getChildAt(i);
                // CheckBox component is made up of box skin and label TextField
                if (!(c is TextField)) {
                    c.x = (w - c.width) / 2;
                    c.y = (h - c.height) / 2;
                }
            }

            if (data && data is PickFilterRow) {
                var pfr:PickFilterRow = data as PickFilterRow

                if (_grid && _grid.useItemEnablementPropertyToEnableSelection) {
                    var itemEnablementProperty:String = _grid.itemEnablementProperty;
                    if (pfr.hasOwnProperty(itemEnablementProperty)) {
                        var itemEnablementValue:Boolean = pfr[itemEnablementProperty] as Boolean;
                        this.enabled = itemEnablementValue;
                    }
                    else {
                        this.enabled = false;
                    }
                }

            }
        }


        override public function set listData(value:BaseListData):void {
            super.listData = value;

            _adgListData = AdvancedDataGridListData(value);
            if (_adgListData)
                _grid = PickFilterGrid(_adgListData.owner);
        }

    }
}